const path = require('path');
const child = require('child_process');

const better_sqlite3 = require.resolve('better-sqlite3');
const better_sqlite3_root = path.join(
  better_sqlite3.slice(0, better_sqlite3.lastIndexOf('node_modules')),
  'node_modules/better-sqlite3'
);

console.log('process.platform:', process.platform);

// 1. 使用绝对路径调用 npm/node-gyp
const npmCommand = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const args = [
  'rebuild',  // 直接使用 `rebuild` 而不是 `run build-release`
  'better-sqlite3',
  `--target=${process.versions.electron}`,
  '--runtime=electron',
  '--dist-url=https://electronjs.org/headers',
  '--build-from-source',  // 强制从源码编译,
  '--verbose'  // 显示详细日志
];

console.log('Running command:', npmCommand, args.join(' '));

// 2. 显式设置环境变量
const env = {
  ...process.env,
  npm_config_target: process.versions.electron,
  npm_config_runtime: 'electron',
  npm_config_disturl: 'https://electronjs.org/headers',
  npm_config_build_from_source: 'true',
  npm_config_debug: 'true',  // 启用调试模式
};

try {
// 使用 spawnSync 获取更详细的错误输出
  const result = child.spawnSync(npmCommand, args, {
    cwd: better_sqlite3_root,
    stdio: 'inherit',
    env,  // 注入环境变量
    shell: true  // Windows 需要 shell 支持
  });
  console.log(result, "----> result");
  
  if (result.status !== 0) {
    console.error('❌ 编译失败，请检查以下内容：');
    console.log('1. 确保安装了 Python 3.7+ 和 Visual Studio Build Tools（Windows）');
    console.log('2. 尝试降级 Node.js 到 v18（如果当前是 v20+）');
    console.log('3. 查看完整错误日志：');
    console.log(result.stderr?.toString() || result.stdout?.toString());
    process.exit(1);
  } else {
    console.log('✅ 编译成功！');
  }
} catch (error) {
  console.error(error);
  console.error("异常");
}